/*
 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
 * All rights reserved.
 *
 * This software is a confidential and proprietary information of Samsung
 * Electronics, Inc. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with Samsung Electronics.
 */

package com.photobook.base.event;

import java.io.Serializable;

import roboguice.activity.event.OnCreateEvent;
import roboguice.activity.event.OnDestroyEvent;
import roboguice.event.EventManager;
import roboguice.event.Observes;
import roboguice.inject.ContextSingleton;
import roboguice.receiver.RoboBroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import com.google.inject.Inject;

/**
 * @author diego.freitas
 * 
 */
@ContextSingleton
public class BroadcastEventManager {

	private static final String EVENT_RESULT = "event_resubr.com.poc.lt";

	/**
	 * The event manager of application
	 */
	@Inject
	private EventManager evtManager;

	/**
	 * Any context
	 */
	@Inject
	private Context context;

	private final BroadcastReceiver receiver = new RoboBroadcastReceiver() {

		@Override
		protected void handleReceive(final Context context, final Intent intent) {
			evtManager.fire(intent.getSerializableExtra(EVENT_RESULT));
		}

	};

	/**
	 * True if the Broadcast event manager is initialized
	 */
	private boolean initialized;

	/**
	 * Register Receiver to FacebookManager, we have to register this receiver
	 * specially to FacebookManager because it is a @Singleton and because of
	 * that it does not listen events
	 * 
	 * @param event
	 */
	public void onCreate(@Observes final OnCreateEvent event) {
		initialized = true;
		LocalBroadcastManager.getInstance(context).registerReceiver(receiver,
				new IntentFilter(BroadcastEventManager.class.getName()));
	}

	/**
	 * Unregister Receiver to FacebookManager, we have to register this receiver
	 * specially to FacebookManager because it is a @Singleton and because of
	 * that it does not listen events
	 * 
	 * @param event
	 */
	public void onDestroy(@Observes final OnDestroyEvent event) {
		initialized = false;
		LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
	}

	/**
	 * Return true if the register is initialized
	 * 
	 * @return
	 */
	public boolean isInitialized() {
		return initialized;
	}

	/**
	 * @param class1
	 * @param result
	 */
	public void fireEvent(final Serializable result) {
		final Intent intent = new Intent(BroadcastEventManager.class.getName());
		intent.putExtra(EVENT_RESULT, result);
		LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
	}

}
